import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Progress, Table, Tooltip, Button } from 'antd';
import {
  DashboardOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  UserOutlined,
  FileTextOutlined,
  ShoppingCartOutlined,
  EyeOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import './index.less';

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [visitData, setVisitData] = useState<any[]>([]);
  const [salesData, setSalesData] = useState<any[]>([]);
  const [cpuData, setCpuData] = useState<number[]>([]);
  const [memoryData, setMemoryData] = useState<number[]>([]);
  
  // 模拟数据加载
  useEffect(() => {
    setTimeout(() => {
      setVisitData(generateVisitData());
      setSalesData(generateSalesData());
      setCpuData(generateCpuData());
      setMemoryData(generateMemoryData());
      setLoading(false);
    }, 1500);
    
    // 模拟数据更新
    const timer = setInterval(() => {
      setCpuData(generateCpuData());
      setMemoryData(generateMemoryData());
    }, 5000);
    
    return () => clearInterval(timer);
  }, []);

  // 模拟访问数据
  const generateVisitData = () => {
    const baseValue = Math.random() * 1000 + 3000;
    const visitData = [];
    const fakeY = [7, 5, 4, 2, 4, 7, 5, 6, 5, 9, 6, 3, 1, 5, 3, 6, 5];
    for (let i = 0; i < fakeY.length; i += 1) {
      visitData.push({
        x: new Date(new Date().getTime() - 60 * 60 * 1000 * (fakeY.length - i - 1)).toLocaleString(),
        y: Math.floor(Math.random() * 100 + baseValue - 1000),
      });
    }
    return visitData;
  };

  // 模拟销售数据
  const generateSalesData = () => {
    const data = [];
    for (let i = 0; i < 12; i += 1) {
      data.push({
        x: `${i + 1}月`,
        y: Math.floor(Math.random() * 20) + 5,
      });
    }
    return data;
  };

  // 模拟CPU数据
  const generateCpuData = () => {
    const data = [];
    for (let i = 0; i < 20; i += 1) {
      data.push(Math.floor(Math.random() * 40) + 30);
    }
    return data;
  };

  // 模拟内存数据
  const generateMemoryData = () => {
    const data = [];
    for (let i = 0; i < 20; i += 1) {
      data.push(Math.floor(Math.random() * 30) + 40);
    }
    return data;
  };

  // 订单列表数据
  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'id',
      key: 'id',
      render: (text: string) => <span className="order-id">{text}</span>,
    },
    {
      title: '用户',
      dataIndex: 'user',
      key: 'user',
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (text: number) => <span className="amount">¥ {text.toFixed(2)}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: string) => {
        let className = '';
        if (text === '已完成') className = 'status-success';
        if (text === '处理中') className = 'status-processing';
        if (text === '待处理') className = 'status-pending';
        
        return <span className={`status-tag ${className}`}>{text}</span>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: () => (
        <div className="action-buttons">
          <Tooltip title="查看详情">
            <Button type="link" icon={<EyeOutlined />} size="small" className="view-btn" />
          </Tooltip>
        </div>
      ),
    },
  ];

  const orderData = Array.from({ length: 5 }, (_, i) => {
    const statuses = ['已完成', '处理中', '待处理'];
    const randomStatus = statuses[Math.floor(Math.random() * statuses.length)];
    
    return {
      key: i,
      id: `ORD${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
      user: `用户${Math.floor(Math.random() * 1000) + 1}`,
      date: new Date().toLocaleDateString(),
      amount: Math.random() * 1000 + 100,
      status: randomStatus,
    };
  });

  // 访问量图表配置
  const visitChartOption = {
    grid: {
      top: 40,
      right: 20,
      bottom: 40,
      left: 50,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      backgroundColor: 'rgba(10, 30, 66, 0.85)',
      borderColor: 'rgba(0, 180, 255, 0.4)',
      borderWidth: 1,
      textStyle: {
        color: '#a3daff',
      },
    },
    xAxis: {
      type: 'category',
      data: visitData.map(item => item.x),
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      axisLabel: {
        color: '#a3daff',
        formatter: (value: string) => {
          return value.split(' ')[1];
        },
      },
      axisTick: {
        alignWithLabel: true,
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.1)',
          type: 'dashed',
        },
      },
      axisLabel: {
        color: '#a3daff',
      },
    },
    series: [
      {
        name: '访问量',
        type: 'bar',
        data: visitData.map(item => item.y),
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(0, 218, 255, 0.9)',
              },
              {
                offset: 1,
                color: 'rgba(0, 143, 255, 0.3)',
              },
            ],
          },
          borderRadius: [4, 4, 0, 0],
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(0, 255, 208, 1)',
                },
                {
                  offset: 1,
                  color: 'rgba(0, 186, 255, 0.5)',
                },
              ],
            },
          },
        },
      },
    ],
  };

  // 销售额图表配置
  const salesChartOption = {
    grid: {
      top: 40,
      right: 20,
      bottom: 40,
      left: 50,
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(10, 30, 66, 0.85)',
      borderColor: 'rgba(0, 180, 255, 0.4)',
      borderWidth: 1,
      textStyle: {
        color: '#a3daff',
      },
    },
    xAxis: {
      type: 'category',
      data: salesData.map(item => item.x),
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      axisLabel: {
        color: '#a3daff',
      },
      axisTick: {
        alignWithLabel: true,
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.1)',
          type: 'dashed',
        },
      },
      axisLabel: {
        color: '#a3daff',
      },
    },
    series: [
      {
        name: '销售额',
        type: 'line',
        data: salesData.map(item => item.y),
        lineStyle: {
          color: '#00c8ff',
          width: 3,
        },
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#00c8ff',
          borderColor: 'rgba(0, 240, 255, 0.8)',
          borderWidth: 2,
        },
        emphasis: {
          itemStyle: {
            color: '#00e1ff',
            borderColor: 'rgba(0, 240, 255, 1)',
            borderWidth: 3,
            shadowColor: 'rgba(0, 200, 255, 0.9)',
            shadowBlur: 10,
          },
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(0, 180, 255, 0.3)',
              },
              {
                offset: 1,
                color: 'rgba(0, 180, 255, 0.05)',
              },
            ],
          },
        },
      },
    ],
  };

  // 系统资源图表配置
  const resourceChartOption = {
    grid: {
      top: 40,
      right: 20,
      bottom: 20,
      left: 50,
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(10, 30, 66, 0.85)',
      borderColor: 'rgba(0, 180, 255, 0.4)',
      borderWidth: 1,
      textStyle: {
        color: '#a3daff',
      },
    },
    legend: {
      data: ['CPU', '内存'],
      top: 10,
      textStyle: {
        color: '#a3daff',
      },
      icon: 'rect',
    },
    xAxis: {
      type: 'category',
      data: Array(20).fill(0).map((_, i) => i),
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      axisLabel: {
        color: '#a3daff',
        formatter: () => '',
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLine: {
        show: true,
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.2)',
        },
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 180, 255, 0.1)',
          type: 'dashed',
        },
      },
      axisLabel: {
        color: '#a3daff',
        formatter: '{value}%',
      },
    },
    series: [
      {
        name: 'CPU',
        type: 'line',
        data: cpuData,
        lineStyle: {
          color: '#00d0ff',
          width: 2,
        },
        symbol: 'none',
        emphasis: {
          lineStyle: {
            width: 3,
          },
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(0, 208, 255, 0.3)',
              },
              {
                offset: 1,
                color: 'rgba(0, 208, 255, 0)',
              },
            ],
          },
        },
      },
      {
        name: '内存',
        type: 'line',
        data: memoryData,
        lineStyle: {
          color: '#00a8ff',
          width: 2,
        },
        symbol: 'none',
        emphasis: {
          lineStyle: {
            width: 3,
          },
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(0, 168, 255, 0.3)',
              },
              {
                offset: 1,
                color: 'rgba(0, 168, 255, 0)',
              },
            ],
          },
        },
      },
    ],
  };

  const onRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      setVisitData(generateVisitData());
      setSalesData(generateSalesData());
      setCpuData(generateCpuData());
      setMemoryData(generateMemoryData());
      setLoading(false);
    }, 1000);
  };

  return (
    <div className="dashboard-container">
      <div className="dashboard-header">
        <div className="dashboard-title">
          <DashboardOutlined /> 系统仪表盘
        </div>
        <div className="dashboard-actions">
          <Button 
            type="text" 
            icon={<ReloadOutlined />} 
            onClick={onRefresh}
            loading={loading}
            className="refresh-btn"
          >
            刷新
          </Button>
        </div>
      </div>
      
      <Row gutter={[24, 24]}>
        <Col xs={24} sm={12} md={6}>
          <Card className="stats-card" loading={loading}>
            <Statistic
              title="总访问量"
              value={112893}
              valueStyle={{ color: '#00c8ff' }}
              prefix={<UserOutlined />}
              suffix={
                <span className="trend up">
                  <ArrowUpOutlined /> 12%
                </span>
              }
            />
            <div className="data-trend">
              <Progress 
                percent={92} 
                size="small" 
                showInfo={false}
                strokeColor={{
                  '0%': '#00a8ff',
                  '100%': '#00e1ff',
                }}
                trailColor="rgba(0, 180, 255, 0.1)"
              />
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stats-card" loading={loading}>
            <Statistic
              title="订单总数"
              value={8846}
              valueStyle={{ color: '#00c8ff' }}
              prefix={<FileTextOutlined />}
              suffix={
                <span className="trend up">
                  <ArrowUpOutlined /> 9%
                </span>
              }
            />
            <div className="data-trend">
              <Progress 
                percent={75} 
                size="small" 
                showInfo={false}
                strokeColor={{
                  '0%': '#00a8ff',
                  '100%': '#00e1ff',
                }}
                trailColor="rgba(0, 180, 255, 0.1)"
              />
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stats-card" loading={loading}>
            <Statistic
              title="销售额"
              value={9280}
              valueStyle={{ color: '#00c8ff' }}
              prefix="¥"
              suffix={
                <span className="trend up">
                  <ArrowUpOutlined /> 18%
                </span>
              }
            />
            <div className="data-trend">
              <Progress 
                percent={88} 
                size="small" 
                showInfo={false}
                strokeColor={{
                  '0%': '#00a8ff',
                  '100%': '#00e1ff',
                }}
                trailColor="rgba(0, 180, 255, 0.1)"
              />
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card className="stats-card" loading={loading}>
            <Statistic
              title="转化率"
              value={25.3}
              precision={1}
              valueStyle={{ color: '#00c8ff' }}
              prefix={<ShoppingCartOutlined />}
              suffix={
                <span className="trend down">
                  <ArrowDownOutlined /> 4%
                </span>
              }
            />
            <div className="data-trend">
              <Progress 
                percent={61} 
                size="small" 
                showInfo={false}
                strokeColor={{
                  '0%': '#00a8ff',
                  '100%': '#00e1ff',
                }}
                trailColor="rgba(0, 180, 255, 0.1)"
              />
            </div>
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[24, 24]} style={{ marginTop: '24px' }}>
        <Col xs={24} md={12}>
          <Card className="chart-card" title="访问量趋势" loading={loading}>
            <ReactECharts option={visitChartOption} style={{ height: '300px' }} />
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card className="chart-card" title="销售趋势" loading={loading}>
            <ReactECharts option={salesChartOption} style={{ height: '300px' }} />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[24, 24]} style={{ marginTop: '24px' }}>
        <Col xs={24} md={12}>
          <Card className="chart-card" title="系统资源" loading={loading}>
            <ReactECharts option={resourceChartOption} style={{ height: '220px' }} />
          </Card>
        </Col>
        <Col xs={24} md={12}>
          <Card className="table-card" title="最近订单" loading={loading}>
            <Table 
              columns={orderColumns} 
              dataSource={orderData} 
              pagination={false} 
              size="small"
              className="tech-table"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard; 